iT邦幫忙

2024 iThome 鐵人賽

DAY 2
0
自我挑戰組

30 天 vueuse 原始碼閱讀與實作系列 第 2

[Day 2] useThrottleFn - 序章

  • 分享至 

  • xImage
  •  

官方文件連結:https://vueuse.org/shared/useThrottleFn/

今天就從 useThrottleFn 開始吧!核心基本上就是熟悉的那個 throttle,再加上一些有的沒的(不是

基本架構

Wrapper Function

vueuse 原始碼檔案:https://github.com/vueuse/vueuse/blob/main/packages/shared/useThrottleFn/index.ts

// src/compositions/useThrottleFn.js 
import { throttleFilter } from '@/utils/filter'

export function useThrottleFn(fn, ms) {
  return throttleFilter(fn, ms)
}

核心邏輯

vueuse 原始碼檔案:https://github.com/vueuse/vueuse/blob/main/packages/shared/utils/filters.ts#L147

// src/utils/filter.js
export function throttleFilter(fn, ms) {
  return fn
}

Demo

vueuse 原始碼檔案:https://github.com/vueuse/vueuse/blob/main/packages/shared/useThrottleFn/demo.vue

<!-- src/components/UseThrottleFnDemo.vue -->
<script setup>
import { ref } from 'vue'
import { useThrottleFn } from '@/compositions/useThrottleFn'

const clicked = ref(0)
const updated = ref(0)

const throttledFn = useThrottleFn(() => {
  updated.value += 1
})

function clickHandler() {
  clicked.value += 1
  throttledFn()
}
</script>

<template>
  <h2>UseThrottleFnDemo</h2>
  <div class="box" @click="clickHandler">
    <span>click throttle box</span>
  </div>
  <div>Button clicked: {{ clicked }}</div>
  <div>Event handler called: {{ updated }}</div>
</template>

<style>
.box {
  width: 300px;
  height: 300px;
  background: #ccc;
}
</style>

接下來會從最基本的 throttle 功能開始實作,核心邏輯會寫在 throttleFilter 這個 function,在這邊陸續把功能補齊。

GitHub:https://github.com/RhinoLee/30days_vue/pull/4/files


上一篇
[Day 1] Intro
下一篇
[Day 3] useThrottleFn - 核心邏輯
系列文
30 天 vueuse 原始碼閱讀與實作13
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言